package haoi.dt.impl;

import haoi.dt.utils.SequenceUtil;
import org.apache.http.conn.HttpHostConnectException;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ImageServiceImpl implements dt.ImageService {

    public dt.utils.HttpClientUtils httpClientUtils = new dt.utils.HttpClientUtils();

    public static dt.ImageService imageService = new ImageServiceImpl();
    private static Map<String,String> subjectAnswerMap = new LinkedHashMap<String,String>();
    /**
     * 打印信息的类，是一个线程。
     */
    static class Printer extends Thread{
        private static List<String> subjectList = new ArrayList<String>();
        boolean running = false;
        public void start(){
            this.running = true;
            super.start();
        }
        public void run(){
            try {
                //休眠500毫秒
                Thread.sleep(500);
//                System.out.println("Printer begin!");
                while (running){
                    synchronized(this) {
                        while ((subjectList.size() == 0) && running){
                            //如果任务列表为空，而且线程还允许运行，则等待任务
//                            System.out.println("wait begin!");
                            //该线程进入等待状态，直到被其他线程唤醒
                            wait();
//                            System.out.println("wait end!");
                        }
                    }
                    if (running) {
                        if (subjectList != null && subjectList.size() > 0) {

                            for(int i = 0 ; i < subjectList.size() ; i++){
                                String it = subjectList.get(i);
                                Map<String, Object> parameterMap = new HashMap<String, Object>();
                                parameterMap.put("ID", it);
                                parameterMap.put("r", SequenceUtil.getSeqByRandom());
                                String responseStr = imageService.getAnswer(parameterMap);
                                if(responseStr==null || "".equals(responseStr)){
                                    //休眠1000毫秒
                                    Thread.sleep(1000);
                                    responseStr = imageService.getAnswer(parameterMap);
                                }
                                subjectAnswerMap.put(it, responseStr);
                                subjectList.remove(i);
//                                System.out.println("add subjectAnswerMap: " + subjectId+"="+responseStr);
                                running = false ;	//结束线程检测
                            }


                        }
                    }
                }
//                System.out.println("Printer end!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /**
         * 添加待打印的任务
         */
        public void addTask(String subjectId){

            synchronized (this){
                subjectList.add(subjectId);
                //唤醒其他等待的线程
//                System.out.println("addTask notify!");
                notify();
                //notifyAll();
            }
        }
        /**
         * 停止线程
         */
        public void stopPrinter(){
            this.running = false;
            synchronized (this){
                //唤醒其他等待的线程
                System.out.println("stopPrinter notify!");
                notify();
            }
        }
    }




    public static void main(String[] args) {
        Printer printer = new Printer();
        //启动打印线程
        printer.start();
        //添加任务
        try {
            Thread.sleep(500);
            for (int i=0; i<5; i++){
                //休眠500毫秒
                Thread.sleep(500);
                printer.addTask("The task " + i);
            }
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
        printer.stopPrinter();
    }
    @Override
    public  String getAccessPath() {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        String responseStr = httpClientUtils.get("http://2.haoi23.net/svlist.html", paramMap);
        if(responseStr == null){
            return null;
        }
        String host = null;
        Pattern pattern = Pattern.compile("===.*\\+\\+\\+");
        Matcher matcher = pattern
                .matcher(responseStr);
        if (matcher.find())
            host = matcher.group(0);
//		host = host.replace("\\=\\=\\=", "");
//		host = host.replace("\\+\\+\\+", "");
        host = host.substring(3, host.length()-3);
        String[] s = host.split("--");
        String actionUrl = "http://" + s[0];
        return actionUrl;
    }
    /**
     * 获取 验证码具体数据
     * @param subjectId
     * @return
     */
    public static String getAnswer(String subjectId){
        return subjectAnswerMap.get(subjectId);
    }
    @Override
    public String sendFile(Map<String, Object> paramMap, String imagePath) {
        String host = imageService.getAccessPath();
        dt.utils.ImageChange64Bit bit = new dt.utils.ImageChange64Bit();
        @SuppressWarnings("static-access")
        String image = bit.GetImageStr(imagePath);//"d:\\test\\captcha.jpg"
        paramMap.put("DaiLi", "haoi");//【不公开】
        paramMap.put("Ver", "web2");//【不公开】
        paramMap.put("Img", image);

        String subjectId = httpClientUtils.post(host+"/UPLOADBASE64.ASPX", paramMap);

        Printer printer = new Printer();
        //启动打印线程
        printer.start();
        //添加任务
        printer.addTask(subjectId);

        return subjectId;
    }

    @Override
    public String getAnswer(Map<String, Object> paramMap){
        String host = imageService.getAccessPath();
        if(host == null){
            return null;
        }
        String responseStr = httpClientUtils.post(host+"/GetAnswer.aspx", paramMap);
        return responseStr;

    }
    @Override
    public String sendError(Map<String, Object> paramMap) {
        String host = imageService.getAccessPath();
        String responseStr = httpClientUtils.post(host+"/SendError.aspx", paramMap);
        return responseStr;
    }
    @Override
    public String getPoint(Map<String, Object> paramMap) {
        String host = imageService.getAccessPath();
        String responseStr = httpClientUtils.post(host+"/GetPoint.aspx", paramMap);
        return responseStr;
    }

}
